import { loadEnv } from "vite";
import type { UserConfig, ConfigEnv, PluginOption } from "vite";
import vue from "@vitejs/plugin-vue";
// tsx插件引入
import vueJsx from "@vitejs/plugin-vue-jsx";
// 自动引入ref,reactive等等等
import AutoImport from "unplugin-auto-import/vite";

import viteCompression from "vite-plugin-compression";

import { visualizer } from "rollup-plugin-visualizer";

import { createSvgIconsPlugin } from "vite-plugin-svg-icons";

import vueSetupExtend from "vite-plugin-vue-setup-extend";

import { resolve } from "path";

const root = process.cwd();

export default ({ command, mode }: ConfigEnv): UserConfig => {
	const env: any = loadEnv(mode, root);

	const { VITE_APP_PORT, VITE_APP_REPORT, VITE_APP_BUILD_GZIP, VITE_APP_OPEN } = env;

	const vitePlugins: (PluginOption | PluginOption[])[] = [
		vue(),
		vueJsx(),
		AutoImport({
			imports: ["vue"],
		}),
		vueSetupExtend(),
		// 使用 svg 图标
		createSvgIconsPlugin({
			iconDirs: [resolve(__dirname, "./src/assets/svg")],
			symbolId: "icon-[name]",
		}),
	];

	// vite-plugin-compression gzip compress
	if (VITE_APP_BUILD_GZIP === "true") {
		vitePlugins.push(
			viteCompression({
				verbose: true,
				disable: false,
				threshold: 10240,
				algorithm: "gzip",
				ext: ".gz",
			})
		);
	}

	// rollup-plugin-visualizer 是否生成包预览(分析依赖包大小,方便做优化处理)
	if (VITE_APP_REPORT === "true") {
		vitePlugins.push(visualizer());
	}

	// 代理
	const proxy = {
		"/api": {
			target: "http://10.33.0.60:6012/",
			ws: true,
			changeOrigin: true,
			rewrite: (path: string) => path.replace(/^\/api/, ""),
		},
	};

	return {
		root,

		base: env.VITE_BASE_PATH,

		plugins: vitePlugins,

		server: {
			host: "0.0.0.0",
			port: Number(VITE_APP_PORT || 2333),
			open: VITE_APP_OPEN === "true",
			cors: true,
			proxy,
		},

		resolve: {
			// 别名配置
			alias: [
				{
					find: /@\//,
					replacement: `${resolve(__dirname, "./src")}/`,
				},
			],
		},

		optimizeDeps: {
			include: ["vue", "vue-router", "pinia", "axios", "@vueuse/core", "lodash", "element-plus"],
		},
	};
};
